//
//  ShellExchangeView.m
//  ShellWallert
//
//  Created by lvzhao on 2020/2/15.
//  Copyright © 2020 VV. All rights reserved.
//

#import "ShellExchangeView.h"
#import "ShellExchangeViewModel.h"



@interface ShellExchangeView()<UITextFieldDelegate>

@property (nonatomic,strong) ShellExchangeViewModel *viewModel;

///laft的Btn
@property (nonatomic,strong) UIButton *leftBtn;

//right的Btn
@property (nonatomic,strong) UIButton *rightBtn;

///兌換按鈕
@property (nonatomic,strong) UIButton *reverseBtn;

//转出
@property (nonatomic,strong) UITextField *transferTextField;

//收到
@property (nonatomic,strong) UITextField *incomeTextField;

//汇率
@property (nonatomic,strong) UILabel *rateNumLab;

//余额
@property (nonatomic,strong) UILabel *balanceNumLab;


@end

@implementation ShellExchangeView

- (instancetype)initViewModel:(LZBaseViewModel *)viewModel
{
    self = [super init];
    if (self) {
        self.backgroundColor = UIColorHex(0x04172A);
        self.viewModel = (ShellExchangeViewModel *)viewModel;
        [self setupView];
    }
    return self;
}


#pragma mark - setupView
- (void)setupView{
    
    UIScrollView *scrollView = [[UIScrollView alloc] init];
    scrollView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    [self addSubview:scrollView];
    [scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.top.mas_equalTo(0);
    }];
    
    //内容
    UIView *contentView = [[UIView alloc] init];
    contentView.backgroundColor = UIColor.clearColor;
    [scrollView addSubview:contentView];
    [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.bottom.and.right.equalTo(scrollView).with.insets(UIEdgeInsetsZero);
        make.width.equalTo(scrollView);
    }];
    
    
    UIView *exchangeView = [[UIView alloc] init];
    exchangeView.backgroundColor = UIColorHex(0x061D34);
    [contentView addSubview:exchangeView];
    [exchangeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.mas_equalTo(15);
        make.width.mas_equalTo(K_SCREENWIDTH - 30);
        make.height.mas_equalTo(220);
    }];
    exchangeView.cornerRadius = 6;
    
    CGFloat currencyBtnW = (K_SCREENWIDTH - 30 - 30)/2.0;
    [exchangeView addSubview:self.leftBtn];
    [self.leftBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.width.mas_equalTo(currencyBtnW);
        make.height.mas_equalTo(30);
        make.top.mas_equalTo(23);
    }];
    
    [exchangeView addSubview:self.rightBtn];
    [self.rightBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-15);
        make.width.mas_equalTo(currencyBtnW);
        make.height.mas_equalTo(30);
        make.top.mas_equalTo(23);
    }];
    
    
    
    UIView *lineView = [[UIView alloc] init];
    lineView.backgroundColor = UIColorHex(0x3A4355);
    [exchangeView addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.top.mas_equalTo(75);
        make.height.mas_equalTo(1);
    }];
    

    [exchangeView addSubview:self.reverseBtn];
    [self.reverseBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(lineView.mas_centerY);
        make.centerX.mas_equalTo(exchangeView.mas_centerX);
        make.width.mas_equalTo(30);
        make.height.mas_equalTo(30);
    }];
    

    [self.leftBtn SG_imagePositionStyle:SGImagePositionStyleDefault spacing:5];
    [self.rightBtn SG_imagePositionStyle:SGImagePositionStyleDefault spacing:5];

    
    ///!!!转出数量
    [exchangeView addSubview:self.transferTextField];
    [self.transferTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.top.mas_equalTo(self.reverseBtn.mas_bottom).mas_offset(20);
        make.width.mas_equalTo(currencyBtnW);
        make.height.mas_equalTo(22);
    }];
    
    [exchangeView addSubview:self.incomeTextField];
    [self.incomeTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-15);
        make.top.mas_equalTo(self.reverseBtn.mas_bottom).mas_offset(20);
        make.width.mas_equalTo(currencyBtnW);
        make.height.mas_equalTo(22);
    }];
    
    
    UIImageView *imageView = [[UIImageView alloc] initWithImage:k_imageName(@"icon_change_exchange")];
    [exchangeView addSubview:imageView];
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
        make.width.mas_equalTo(K_SCREENWIDTH - 30);
        make.height.mas_equalTo(87);
    }];

    
    ///!!!余额
    UILabel *balanceLab = [UILabel lz_createLabWithTextColor:UIColorHex(0x678DA8) font:k_textFont(12)];
    balanceLab.text = LZLocalizedString(@"余额");
    CGFloat balanceWidth = [balanceLab.text lz_textWidthWithFontSize:balanceLab.font withMaxHeight:19];
    [imageView addSubview:balanceLab];
    [balanceLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(25);
        make.left.mas_equalTo(15);
        make.width.mas_equalTo(balanceWidth);
        make.height.mas_equalTo(17);
    }];
    
    
    [imageView addSubview:self.balanceNumLab];
    [self.balanceNumLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(balanceLab.mas_centerY);
        make.left.mas_equalTo(balanceLab.mas_right).mas_offset(10);
        make.width.mas_equalTo(200);
        make.height.mas_equalTo(17);
    }];


    ///!!!汇率
    UILabel *rateLabel = [UILabel lz_createLabWithTextColor:UIColorHex(0x678DA8) font:k_textFont(12)];
    rateLabel.text = LZLocalizedString(@"汇率");
    CGFloat rateWidth = [rateLabel.text lz_textWidthWithFontSize:rateLabel.font withMaxHeight:19];
    [imageView addSubview:rateLabel];
    [rateLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(balanceLab.mas_bottom).mas_offset(8);
        make.left.mas_equalTo(15);
        make.width.mas_equalTo(rateWidth);
        make.height.mas_equalTo(20);
    }];
    
    
    [imageView addSubview:self.rateNumLab];
    [self.rateNumLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(rateLabel.mas_centerY);
        make.left.mas_equalTo(rateLabel.mas_right).mas_offset(10);;
        make.right.mas_equalTo(-15);
        make.height.mas_equalTo(20);
    }];
    
    
    //兑换按钮
    UIButton *exchangeBtn = [UIButton lz_buttonTitle:LZLocalizedString(@"兑换") titleColor:UIColorHex(0xFFFFFF) fontSize:17];
    [exchangeBtn setGradientBackgroundWithColors:@[UIColorHex(0x65DFFE),UIColorHex(0x2C6FE)] locations:@[@(0), @(1.0f)] startPoint:CGPointMake(1, 0.5) endPoint:CGPointMake(0, 0.5)];
    [contentView addSubview:exchangeBtn];
    [exchangeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(exchangeView.mas_centerX);
        make.width.mas_equalTo(exchangeView);
        make.top.mas_equalTo(exchangeView.mas_bottom).mas_offset(20);
        make.height.mas_equalTo(45);
    }];
    exchangeBtn.cornerRadius = 6;
    @weakify(self);
    [exchangeBtn addTarget:self action:@selector(exchangeClick:) forControlEvents:UIControlEventTouchUpInside];
    
    [contentView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(exchangeBtn.mas_bottom).mas_offset(30);
    }];
    
    [self.viewModel.reloadSubject subscribeNext:^(id  _Nullable x) {
        @strongify(self);
        [self reloadExchange:[x integerValue]];

    }];
    
    [[self.transferTextField rac_textSignal] subscribeNext:^(NSString * _Nullable x) {
        @strongify(self);
        [self calculationBuyNum];
    }];
    
    [[self.incomeTextField rac_textSignal] subscribeNext:^(NSString * _Nullable x) {
        @strongify(self);
        [self calculationSellNum];
    }];
    
    //闪兑配置
    [self.viewModel getExchangeConfig];

    /**
     点usdt的兑换。
     默认usdt换btc

     点btc的兑换，默认btc兑换usdt
     点eth的兑换，默认eth兑换usdt
    */
    if([self.viewModel.wallertModel.coinCode isEqualToString:@"ETH"]){
        [self.leftBtn setTitle:@"ETH" forState:UIControlStateNormal];
        [self.leftBtn setImage:k_imageName(@"icon_eth") forState:UIControlStateNormal];
        
        [self.rightBtn setTitle:@"USDT" forState:UIControlStateNormal];
        [self.rightBtn setImage:k_imageName(@"icon_usdt") forState:UIControlStateNormal];
        
        
    } else if([self.viewModel.wallertModel.coinCode isEqualToString:@"BTC"]){
        
        [self.leftBtn setTitle:@"BTC" forState:UIControlStateNormal];
        [self.leftBtn setImage:k_imageName(@"icon_btc") forState:UIControlStateNormal];
               
        [self.rightBtn setTitle:@"USDT" forState:UIControlStateNormal];
        [self.rightBtn setImage:k_imageName(@"icon_usdt") forState:UIControlStateNormal];
    }
    
    
    [self.leftBtn addTarget:self action:@selector(selectedCurrenctClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.rightBtn addTarget:self action:@selector(selectedCurrenctClick:) forControlEvents:UIControlEventTouchUpInside];

    
    
}


//选择货币
- (void)selectedCurrenctClick:(UIButton *)sender{
    
    [self endEditing:YES];
    
    //判断再次选择有什么类型货币
    NSMutableArray *titles = [[NSMutableArray alloc] initWithArray:@[@"USDT",@"BTC",@"ETH",LZLocalizedString(@"取消")]];
    [titles removeObject:sender.currentTitle];

    if(sender == self.rightBtn){
        [titles removeObject:self.leftBtn.currentTitle];
    } else {
        [titles removeObject:self.rightBtn.currentTitle];
    }
 
    if([sender.currentTitle isEqualToString:@"USDT"]){
        titles = [NSMutableArray arrayWithArray:@[@"USDT",LZLocalizedString(@"取消")]];
    }
    
    
    @weakify(self);
    [LZToolView showAlertType:LZAlertViewTypeActionSheet withTitle:nil
                      message:nil
                       cancel:nil
                         sure:nil
                   objectDict:@{@"subtitles":titles}
                  cancelBlock:^(id  _Nonnull object){}
                    sureBlock:^(id  _Nonnull object) {
                        NSInteger index = [object integerValue];
                        @strongify(self);
                       
                        
                [sender setTitle:titles[index] forState:UIControlStateNormal];
                NSString *imageName = [NSString stringWithFormat:@"icon_%@",titles[index]].lowercaseString;
                [sender setImage:k_imageName(imageName) forState:UIControlStateNormal];
        
                //刷线汇率
                self.viewModel.symbol = [NSString stringWithFormat:@"%@%@",self.leftBtn.currentTitle,self.rightBtn.currentTitle].lowercaseString;
                self.viewModel.currentCurrncy = self.leftBtn.currentTitle;

                //請求配置
                [self.viewModel getExchangeConfig];
        
    }];
}


//兑换事件
- (void)exchangeClick:(UIButton *)sender{
    
    NSString *transferNum = self.transferTextField.text;
    if(transferNum.length == 0){
        showDelayedDismissTitle(LZLocalizedString(@"请填写转出数量"), nil);
        return;
    }
    [self endEditing:YES];
    @weakify(self);
      [LZToolView showAlertType:LZAlertViewTypeTipAlter withTitle:LZLocalizedString(@"提示") message:LZLocalizedString(@"是否确认兑换?") cancel:@"" sure:LZLocalizedString(@"确定") objectDict:@{@"textAlignment":@(NSTextAlignmentCenter)} cancelBlock:^(id  _Nullable object) {} sureBlock:^(id  _Nullable object) {
          @strongify(self);
          [self.viewModel startExchange:@"" verCode:transferNum];
      }];
}

//刷新兑换的
- (void)reloadExchange:(NSInteger)type{
    switch (type) {
        case 1:{
            
            NSDictionary *dataDictionary = self.viewModel.configDictionary[kResultData];
            
            NSString *rate = [NSString stringWithFormat:@"%@",dataDictionary[@"rate"]?:@"0"];
            self.rateNumLab.text = [NSString stringWithFormat:@"1%@ = %@%@",self.leftBtn.currentTitle,rate,self.rightBtn.currentTitle];
            
            NSString *balance = [NSString stringWithFormat:@"%@",dataDictionary[@"balance"]?:@"0"];
            self.balanceNumLab.text = [NSString stringWithFormat:@"%@ %@",balance,self.viewModel.currentCurrncy];
    
        }
            break;
            
        default:
            break;
    }
}


//计算卖出的数量
- (void)calculationSellNum{

    NSString *transferNum = self.transferTextField.text;
    NSString *incomeNum = self.incomeTextField.text;
    
    NSDictionary *dataDictionary = self.viewModel.configDictionary[kResultData];
    NSString *rate = [NSString stringWithFormat:@"%@",dataDictionary[@"rate"]?:@"0"];
    if([rate isEqualToString:@"0"])return;

    transferNum = [incomeNum yw_stringByDividingBy:rate withRoundingMode:NSRoundDown scale:8];
    if([transferNum isEqualToString:@"0"] && incomeNum.length == 0){
          transferNum = @"";
      }
    self.transferTextField.text = transferNum;

}

//计算收到的数量
- (void)calculationBuyNum{
    
    NSString *transferNum = self.transferTextField.text;
    NSString *incomeNum = self.incomeTextField.text;
    NSDictionary *dataDictionary = self.viewModel.configDictionary[kResultData];
    NSString *rate = [NSString stringWithFormat:@"%@",dataDictionary[@"rate"]?:@"0"];
    incomeNum = [transferNum yw_stringByMultiplyingBy:rate withRoundingMode:NSRoundDown scale:8];
    
    if([incomeNum isEqualToString:@"0"]  && transferNum.length == 0){
        incomeNum = @"";
    }
    self.incomeTextField.text = incomeNum;
}
#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    //    限制只能输入数字
    BOOL isHaveDian = YES;
    if ([string isEqualToString:@" "]) {
        return NO;
    }
    
    if ([textField.text rangeOfString:@"."].location == NSNotFound) {
        isHaveDian = NO;
    }
    if ([string length] > 0) {
        
        unichar single = [string characterAtIndex:0];//当前输入的字符
        if ((single >= '0' && single <= '9') || single == '.') {//数据格式正确
            
            if([textField.text length] == 0){
                if(single == '.') {
                    [textField.text stringByReplacingCharactersInRange:range withString:@""];
                    return NO;
                }
            }
            
            //输入的字符是否是小数点
            if (single == '.') {
                if(!isHaveDian)//text中还没有小数点
                {
                    isHaveDian = YES;
                    return YES;
                    
                }else{
                    [textField.text stringByReplacingCharactersInRange:range withString:@""];
                    return NO;
                }
            }else{
                if (isHaveDian) {//存在小数点
                    
                    //判断小数点的位数
                    NSRange ran = [textField.text rangeOfString:@"."];
                    if (range.location - ran.location <= 4) {
                        return YES;
                    }else{
                        return NO;
                    }
                }else{
                    return YES;
                }
            }
        } else {//输入的数据格式不正确
            [textField.text stringByReplacingCharactersInRange:range withString:@""];
            return NO;
        }
    }
    else
    {
        return YES;
    }
}

#pragma mark - actions
//交换
- (void)reverExchageClick:(UIButton *)sender{
    
    sender.selected = !sender.selected;
    NSString *tempTopTitle = [NSString stringWithFormat:@"%@",self.leftBtn.currentTitle];
    UIImage *tempImage = self.leftBtn.currentImage;
    NSString *tempBottomTitle = [NSString stringWithFormat:@"%@",self.rightBtn.currentTitle];

    
    [self.leftBtn setImage:self.rightBtn.currentImage forState:UIControlStateNormal];
    [self.leftBtn setTitle:tempBottomTitle forState:UIControlStateNormal];

    [self.rightBtn setTitle:tempTopTitle forState:UIControlStateNormal];
    [self.rightBtn setImage:tempImage forState:UIControlStateNormal];
    
    [self.leftBtn SG_imagePositionStyle:SGImagePositionStyleDefault spacing:5];
    [self.rightBtn SG_imagePositionStyle:SGImagePositionStyleDefault spacing:5];
    
    
    
    self.transferTextField.text = @"";
    self.incomeTextField.text = @"";

    self.viewModel.symbol = [NSString stringWithFormat:@"%@%@",self.leftBtn.currentTitle,self.rightBtn.currentTitle].lowercaseString;
    self.viewModel.currentCurrncy = self.leftBtn.currentTitle;

    //請求配置
    [self.viewModel getExchangeConfig];
}


#pragma mark - custool
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self endEditing:YES];
    
}
#pragma mark - get && set
- (UIButton *)reverseBtn{
    if(!_reverseBtn){
        _reverseBtn = [UIButton lz_buttonImageName:@"icon_change" backgroundImageName:@""];
        [_reverseBtn addTarget:self action:@selector(reverExchageClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _reverseBtn;
}


- (UIButton *)leftBtn{
    if(!_leftBtn){
        _leftBtn = [UIButton lz_buttonTitle:@"USDT" titleColor:UIColorHex(0xFFFFFF) fontSize:16];
        [_leftBtn setImage:k_imageName(@"icon_usdt") forState:UIControlStateNormal];
    }
    return _leftBtn;
}

- (UIButton *)rightBtn{
    if(!_rightBtn){
        _rightBtn = [UIButton lz_buttonTitle:@"ETH" titleColor:UIColorHex(0xFFFFFF) fontSize:16];
        [_rightBtn setImage:k_imageName(@"icon_eth") forState:UIControlStateNormal];
    }
    return _rightBtn;
}

- (UITextField *)transferTextField{
    if(!_transferTextField){
        _transferTextField = [[UITextField alloc] init];
        _transferTextField.textColor = UIColorHex(0xFFFFFF);
        _transferTextField.delegate = self;
        _transferTextField.keyboardType = UIKeyboardTypeDecimalPad;
        _transferTextField.font = k_textFont(16);
        _transferTextField.placeholder = LZLocalizedString(@"转出数量");
        _transferTextField.lz_placeholderColor = UIColorHex(0x678DA8);
        _transferTextField.lz_maximumLimit = 15;
    }
    return _transferTextField;
}

- (UITextField *)incomeTextField{
    if(!_incomeTextField){
        _incomeTextField = [[UITextField alloc] init];
        _incomeTextField.textColor = UIColorHex(0xFFFFFF);
        _incomeTextField.delegate = self;
        _incomeTextField.textAlignment = NSTextAlignmentRight;
        _incomeTextField.keyboardType = UIKeyboardTypeDecimalPad;
        _incomeTextField.font = k_textFont(16);
        _incomeTextField.placeholder = LZLocalizedString(@"收到数量");
        _incomeTextField.lz_placeholderColor = UIColorHex(0x678DA8);
        _incomeTextField.lz_maximumLimit = 15;
    }
    return _incomeTextField;
}


- (UILabel *)balanceNumLab{
    if(!_balanceNumLab){
        _balanceNumLab = [UILabel lz_createLabWithTextColor:UIColorHex(0xFFFFFF) font:k_textFont(12)];
    }
    return _balanceNumLab;
    
}

- (UILabel *)rateNumLab{
    if(!_rateNumLab){
        _rateNumLab = [UILabel lz_createLabWithTextColor:UIColorHex(0xFFFFFF) font:k_textFont(12)];
    }
    return _rateNumLab;
    
}




@end
